<?php

namespace App\Listeners;

use App\Events\OrderConfirm;
use App\Events\OrderCreated;
use App\Events\OrderDeleted;
use App\Events\OrderReceived;
use App\Events\OrderRestored;
use App\Jobs\OrderReceivedInfo;
use App\Models\Info;
use App\Models\Order;
use App\Models\User;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

//若引入队列，不可使用ORM对模型进行操作，使用DB
//会导致死循环: 触发ORM 监听器 -> 分发队列任务 -> ORM数据库操作 -> 触发ORM 监听器 -> ....

class OrderEventSubscriber
{
    public function onOrderReceived(OrderReceived $event)
    {
        $receiver = Auth::user();

        //对订单字段的修改
        $order = $event->order;
        $order->receiver = $receiver->openID;
        $order->status = Order::ORDER_STATUS_RUNNING;
        $order->save();

        //引入队列
        //  $order = $event->order;
        //  $receiver = $event->user;
        //
        //  DB::table('orders')->where('id', $order->id)
        //  ->update(['receiver' => $receiver->openID, 'status' => Order::ORDER_STATUS_RUNNING]);
    }

    public function onOrderCreated(OrderCreated $event)
    {
        $user = Auth::user();

        $order = $event->order;
        $order->provider = $user->openID;
        $order->status = Order::ORDER_STATUS_PUBLISHED;
        $order->save();
    }

    public function onOrderDeleted(OrderDeleted $event)
    {
        $order = $event->order;
        $order->status = Order::ORDER_STATUS_CANCELED;
        $order->save();
    }

    public function onOrderRestored(OrderRestored $event)
    {
        $order = $event->order;
        $order->status = Order::ORDER_STATUS_PUBLISHED;
        $order->save();
    }

    public function onOrderConfirm(OrderConfirm $event)
    {
        $order = $event->order;
        $order->status = Order::ORDER_STATUS_FINISHED;
        $order->save();
    }

    /**
     * 注册监听器
     *
     * @param  \Illuminate\Events\Dispatcher  $events
     */
    public function subscribe($event){

        $event->listen(
          'App\Events\OrderReceived',
            'App\Listeners\OrderEventSubscriber@onOrderReceived'
        );
        $event->listen(
            'App\Events\OrderCreated',
            'App\Listeners\OrderEventSubscriber@onOrderCreated'
        );
        $event->listen(
            'App\Events\OrderDeleted',
            'App\Listeners\OrderEventSubscriber@onOrderDeleted'
        );
        $event->listen(
            'App\Events\OrderRestored',
            'App\Listeners\OrderEventSubscriber@onOrderRestored'
        );
        $event->listen(
            'App\Events\OrderConfirm',
            'App\Listeners\OrderEventSubscriber@onOrderConfirm'
        );
    }
}
